<template>
  <Modal
    :styles="{top: '20px',bottom:'20px',width:'90%',}"
    :scrollable=false :closable=true v-model="isShow" :mask-closable="false"  @on-visible-change="modalStatus"
    @on-ok="returnProduct" >

  <div style="padding-bottom: 2rem;min-height: 350px">
    <Row style="text-align: left;padding: 0.5rem 0px;">
      <i-col :xs="24" :sm="8" style="margin-bottom: 0.6rem;">
        <Cascader :data="categoryList" @on-change="categorySelected" change-on-select clearable
                  v-model="selectedCategory" style="width: 310px" placeholder="请选择产品分类" ></Cascader>
      </i-col>
      <i-col :xs="24" :sm="6" style="margin-bottom: 0.6rem;">
        <Input placeholder="请输入产品编号" class="input" style="max-width: 310px" v-model="productSearch.productCode"></Input>
      </i-col>
      <i-col :xs="24" :sm="4" offset="1" style="margin-bottom: 0.6rem;">
        <Button type="primary" icon="search" @click="selectProductsSearch">过滤查询</Button>
      </i-col>
    </Row>
    <!--表格和分页-->
<!--    <Table stripe border  :columns="tableProductTitles" :data="productList" :row-class-name="rowClass"-->
<!--           class="base_table" :max-height="500" style="margin: 1rem 0"-->
<!--           no-data-text="暂无数据" ></Table>-->

    <List style="border-top: 1px solid #e8eaec;border-bottom: 1px solid #e8eaec;margin-top: 1rem;margin-bottom: 1rem;">
      <template v-if="productList.length == 0" >
        <ListItem><div style="width: 100%; text-align: center;">暂无数据</div></ListItem>
      </template>
        <RadioGroup v-model="productRadio" style="width: 100%;">
        <list-item class="list_item" v-for="(item,index) in productList" >
          <div style="width:100%;padding: 0 0.5rem;"  >
            <Row type="flex" justify="space-between" align="middle">
              <i-col  :xs="2" :sm="1">
                <Radio :label="item">&nbsp;</Radio>
              </i-col>
              <i-col  :xs="22" :sm="2" style="text-align: left">
                <img :src="getProductZipImage(item)"
                     style="width:99%;max-width:80px;max-height:80px;"/>
              </i-col>
              <i-col :xs="24" :sm="21" style="text-align: left;padding-left: 0.5rem;" >
                <KeyValueView>#{{index+1}}</KeyValueView>
                <KeyValueView title="编号">{{item.code}}</KeyValueView>
                <KeyValueView title="现价">{{getProductPrice(item)}}</KeyValueView>
                <KeyValueView  title="创建时间" >{{ $tiyBJTime(item.createtime) }}</KeyValueView>
                <KeyValueView oneline title="上/下架时间">{{$tiyBJTime(item.lastmodify)}}</KeyValueView>
                <KeyValueView title="产品名">{{item.name}}</KeyValueView>
              </i-col>
            </Row>
          </div>
        </list-item>
        </RadioGroup>
    </List>

    <div style="float: right;" v-show="productList.length>0">
      <Page :total="page.total" :page-size="page.stepNumber"
            :current="page.currentPage" @on-change="changePage"  :page-size-opts="[40,60,80,120]"
            @on-page-size-change="sizeChange" show-sizer show-elevator/>
    </div>
  </div>
  </Modal>
</template>


<script>

    import {getProductCommonData, createCategoryList,isNotEmpty} from "../js/commonUtils";
    import Vue from 'vue';
    import KeyValueView from "../widgets/KeyValueView";

    export default {
        name: "ProductSelectList",
        props: {
            productListShow: {
                type: Boolean,
                default: false,
                require: true
            },
        },
        data() {
          return {
            isShow:false,
            categoryList: [],
            productSearch: {
                productCode: '',
                category:'',
                categoryLevel:1,
            },
            productList: [],
            productRadio:'',
            selectedCategory:[],
            currentChoose:'',
            currentProduct:-1,
            tableProductTitles:[
              {
                title: '选择',
                key: 'id',
                width: 70,
                align: 'center',
                render: (h, params) => {
                    let id = params.row.id;
                    let flag = false;
                    if (this.currentChoose === id) {
                        flag = true
                    } else {
                        flag = false
                    }
                    let self = this
                    return h('div', [
                        h('Radio', {
                            props: {
                                value: flag
                            },
                            on: {
                                'on-change': () => {
                                    self.currentChoose = id;
                                    self.currentProduct = params.index;
                                }
                            }
                        })
                    ])
                }
              },
               {
                  type: 'index',
                  width: 60,
                  align:'center'
              },
               {
                  title: '编号',
                  key: 'code',
                  align: 'center',
                  width: 170,
              },
              {
                  title: '名称',
                  key: 'name',
                  width: 220,
              },
              {
                  title: '产品图片',
                  key: 'listImgUrl',
                  width: 120,
                  align: 'center',
                  render: (h, params) => {
                      let yunPath = Vue.prototype.$store.getters.imgPrefix;
                      let imageUrl = params.row.productImg;
                      if(params.row.productShowImg!=null&&params.row.productShowImg.zipImgs!=null){
                        let zipImg = params.row.productShowImg.zipImgs;
                        zipImg.forEach(function (item){
                          if(item.size=="200w"){
                            imageUrl=yunPath+item.imagePath;
                          }
                        })
                      }
                      return '' == imageUrl ? '' : h('img', {
                          attrs: {src: imageUrl},
                          style: {'max-width': '100%'},
                      })
                  },
              },
               {
                  title: '现价',
                  key: 'currentPrice',
                  width: 140,
                  align: 'center',
                  render: (h, params) => {
                    return h('div', ((params.row.minPrice && params.row.minPrice != params.row.currentPrice) ? '$' + params.row.minPrice + ' - ' : '') + '$' + params.row.currentPrice);
                  },
              },
               {
                  title: '创建时间',
                  key: 'createtime',
                  width: 160,
                  sortable: 'custom',
                  align: 'center',
                  render: (h, params) => {
                      return h('div', self.$tiyBJTime(params.row.createtime));
                  },
              },
              {
                  title: '上架时间',
                  key: 'lastmodify',
                  sortable: 'custom',
                  align: 'center',
                  render: (h, params) => {
                      let date = new Date(params.row.lastmodify);
                      return h('div', self.$tiyBJTime(params.row.lastmodify));
                  }
              }
          ],
            page: {
                total: 1,
                startIndex: 0,
                stepNumber: 40,
                currentPage: 1,
            }
          }
        },
        components:{KeyValueView},
        methods: {
            init(){
              this.page.total = 1;
              this.page.startIndex = 0;
              this.page.stepNumber = 40;
              this.page.currentPage = 1;
              this.productSearch.productCode = '';
              this.productSearch.category = '';
              this.productSearch.categoryLevel = 1;
              this.productRadio='';
              this.$ySpliceAll(this.productList, this.selectedCategory);
            },
          getProductZipImage(product){
            let yunPath = Vue.prototype.$store.getters.imgPrefix;
            let imageUrl = product.productImg;
            let self=this;
            if(product.productShowImg!=null&&product.productShowImg.zipImgs!=null){
              let zipImg = product.productShowImg.zipImgs;
              zipImg.forEach(function (item){
                if(item.size=="200w"){
                  imageUrl=yunPath+item.imagePath;
                }
              })
            }
            return !imageUrl ? '' : imageUrl;
          },
          getProductPrice(product){
            let price = "";

            if(!product.minPrice){ //正式环境中只要配置了价格就一定有minPrice
              return price;
            }

            let priceArray = [];
            priceArray.push("$" + product.minPrice);
            if(product.currentPrice != product.minPrice){ //不存在有minPrice没有currentPrice的情况
              priceArray.push("$" + product.currentPrice);
            }

            price = priceArray.join(" - ");
            return price;
          },
            selectProductsSearch(){
              this.page.total = 1;
              this.page.startIndex = 0;
              this.page.stepNumber = 40;
              this.page.currentPage = 1;
              this.webList();
            },
            categorySelected(value,selectedData){
              if (0 < selectedData.length) {
                this.productSearch.category = selectedData[selectedData.length-1].value;
                this.productSearch.categoryLevel = selectedData[selectedData.length-1].level;
              } else {
                this.productSearch.category = '';
                this.productSearch.categoryLevel = 1;
              }

            },
            productSelectedChanged()
            {

            },
            changePage(page){
                this.page.currentPage = page;
                this.webList();
            },
            sizeChange(p){
                this.page.stepNumber = p;
            },
            modalStatus(status){
                if(!status){
                    this.$emit("hideProductList")
                }
            },
            webList(){
                let self = this;
                this.$ySpliceAll(this.productList);
                self.$Spin.show();
                self.$apiProduct.selectProducts({
                    "choosed_classify": self.productSearch.category,
                    "classifyLevel": self.productSearch.categoryLevel,
                    "productCode": self.productSearch.productCode,
                    "pageNum": self.page.currentPage,
                    "pageSize": self.page.stepNumber,
                }).then(function (response) {
                    self.$Spin.hide();
                    if (response.success) {
                        let productPage = response.result;
                        self.page.total = productPage.total;
                        productPage.list.forEach(
                            function (item) {
                                self.productList.push(item);
                            }
                        );
                    } else {
                        self.$Message.error(response.errorMessage);
                    }
                });
                self.$Spin.hide();

            },
            rowClass(row,index){
                if (row.id ==this.currentChoose) {
                    return 'row-selected';
                }
                return '';

            },
            returnProduct(){
                if(isNotEmpty(this.productRadio)){
                    this.$emit("receiveProductData",this.productRadio);
                }else{
                    this.$Message.error('请选择产品!');
                }
            }
        },
        watch:{
            productListShow: function (val) {
                if (val) {
                    this.init();
                    let types = [];
                    types.push(3); //列表只查询分类
                    getProductCommonData(this, this.categoryList, types, false, createCategoryList);
                    // this.webList();
                }
                this.isShow = val;
            }
        },


    }
</script>

<style scoped lang="less">
@import  (once,optional) "../css/base";
  .row-selected td{
    background-color: #2db7f5 !important;
    color: #a1b1e2  !important;
  }

  .list_item {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .list_item:hover {
    background: @tiySectionColor;
  }
</style>
